#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include "../tools/str.h"
#include "../global.h"
#include "../debug/debug.h"
#include "set_config_data.h"
#define LINEDATA 128

CONFIG_DATA base_data;


//读取配置文件
int ConfigMiniWeb(const char *file_path, CONFIG_DATA *data){
    FILE *fd;
    int index_key = 0;
    char lineData[LINEDATA]={0};
    fd = fopen(file_path,"r");
    char KeyName[128]={0};
    char KeyValue[512]={0};
    if (fd == NULL)
    {
        WEB_DEBUG(DEBUG_ERROR,"open configure failed (%s)\n",file_path);
        return -1;
    }
    int tableIndex=0;
    while (fgets(lineData,LINEDATA,fd) != NULL)
    {
        
        if ( (lineData[0] >= 'a' && lineData[0] <= 'z') ||
             (lineData[0] >= 'A' && lineData[0] <= 'Z'))
        {
            memset(KeyValue,0,sizeof(KeyValue));
            memset(KeyName,0,sizeof(KeyName));   
            index_key = StrSplit(KeyName,lineData,'=');
            StrSplit(KeyValue,lineData+index_key+1,'\n');
            tableIndex=0;
            while (tableIndex < CONFIG_TABLE_NUM)
            {
                if (StrCmp(ConfigTable[tableIndex].KeyName,KeyName)==EQUAL){
                    ConfigTable[tableIndex].function(&base_data,1,KeyValue);
                    break;
                }
                tableIndex++;

            }
        } 
    }

    WEB_DEBUG(DEBUG_INFO,"ip:%s\n",base_data.ip);
    WEB_DEBUG(DEBUG_INFO,"port:%d\n",base_data.port);
    WEB_DEBUG(DEBUG_INFO,"html path:%s\n",base_data.html_path);
    WEB_DEBUG(DEBUG_INFO,"html file name:%s\n",base_data.html_file_name);
    WEB_DEBUG(DEBUG_INFO,"html file name(404):%s\n",base_data.html_file_404);
    if (base_data.is_use_cgi == YES)
    {
        char tmp_str[CGI_FILE_CLASS_NUM*9]={0};
        WEB_DEBUG(DEBUG_INFO,"use cgi\n");
        for (size_t i = 0; i < CGI_FILE_CLASS_NUM; i++)
        {
            if ((base_data.cgi_file_class.value>>i)&0x1)
            {
                unsigned int len;
                len=StrLenght(tmp_str);
                StrCopy(tmp_str+len,CGIFileClass[i]);
                len=StrLenght(tmp_str);
                StrCopy(tmp_str+len," ");
            }
        }

        WEB_DEBUG(DEBUG_INFO,"cgi file class:%s\n",tmp_str);
        

    }
    
    
    if(fclose(fd)!=0){
        perror("close configure file failed\n");
        return -1;
    }

}


